package com.joro.ejb;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.app.LoggingUtil;
import com.joro.Customer;
import com.joro.Subscription;

/**
 * Session Bean implementation class SubscriptionFacade
 */
@Stateless
public class SubscriptionFacade implements SubscriptionFacadeLocal {

	@PersistenceContext(unitName = "magazine.ejb")
	EntityManager manager;

	/**
	 * Default constructor.
	 */
	public SubscriptionFacade() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void saveSubscription(Subscription pSubscription){
		LoggingUtil.logOperation(LoggingUtil.OPERATION_UPDATE, pSubscription);
		manager.merge(pSubscription);
	}
	
	@Override
	public Collection<Subscription> getSubscriptions(){
		Query query = manager.createQuery("SELECT e FROM Subscription e");
		List<Subscription> resultList = query.getResultList();
		return resultList;
	}
	
	@Override
	public Collection<Subscription> getCustomerSubscriptions(Customer pCustomer){
		Query query = manager.createQuery("SELECT e FROM Subscription e WHERE e.customer = :customer");
		query.setParameter("customer", pCustomer);
		List<Subscription> resultList = query.getResultList();
		return resultList;
	}
	
	public Subscription getSubscriptionById(int pSubscriptionId){
		Query query = manager.createQuery("SELECT e FROM Subscription e WHERE e.id = :id");
		query.setParameter("id", pSubscriptionId);
		List<Subscription> resultList = query.getResultList();
		if(resultList.size() == 0)
			return null;
		return resultList.get(0);
	}

	@Override
	public void deleteSubscription(Subscription pSubscription) {
		LoggingUtil.logOperation(LoggingUtil.OPERATION_DELETE, pSubscription);
		manager.remove(manager.contains(pSubscription) ? pSubscription : manager.merge(pSubscription));		
	}

}
